package ru.st.selenium.applogic2;

import java.io.IOException;

import org.openqa.selenium.Capabilities;
import org.openqa.selenium.WebDriver;

import ru.st.selenium.TracingWebDriver;
import ru.st.selenium.applogic.ApplicationManager;
import ru.st.selenium.applogic.FilmHelper;
import ru.st.selenium.applogic.NavigationHelper;
import ru.st.selenium.applogic.UserHelper;
import ru.st.selenium.util.PropertyLoader;
import ru.stqa.selenium.factory.WebDriverFactory;
import ru.stqa.selenium.factory.WebDriverFactoryMode;

public class ApplicationManager2 implements ApplicationManager {

	private UserHelper userHelper;
	private FilmHelper filmHelper;
	private NavigationHelper navHelper;
//	private DriverBasedHelper driverHelper;
	private String gridHubUrl;
	private String baseUrl;
	
	private Capabilities capabilities;
	private WebDriver driver;
	private static boolean mode = true;
//	private ApplicationManager app;
	
	/*	private static ApplicationManager app;
	
	public static ApplicationManager getInstance() {
		if(app == null){
			app = new ApplicationManager2();
			try {
				app.init();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			}
		return app;
	}
*/
	public ApplicationManager2() throws IOException {
//  public void init() throws IOException {
		baseUrl = PropertyLoader.loadProperty("site.url");
		gridHubUrl = PropertyLoader.loadProperty("grid.url");
		if ("".equals(gridHubUrl)) {
			gridHubUrl = null;
		}
		capabilities = PropertyLoader.loadCapabilities();
		
		if (mode) {
			WebDriverFactory.setMode(WebDriverFactoryMode.THREADLOCAL_SINGLETON);
			mode = false;
		}
		
		driver = WebDriverFactory.getDriver(gridHubUrl, capabilities);
		driver = new TracingWebDriver(driver);
		//driver.setLogLevel(Level.INFO);
		userHelper = new UserHelper2(this);
		filmHelper = new FilmHelper2(this);
		navHelper = new NavigationHelper2(this);
//		driverHelper = new DriverBasedHelper(this);
		
		getNavigationHelper().openStartPage();
	}

	@Override
	public UserHelper getUserHelper() {
		return userHelper;
	}

	@Override
	public FilmHelper getFilmHelper() {
		return filmHelper;
	}

//	@Override
//	public DriverBasedHelper getDriverHelper() {
//		return driverHelper;
//	}

	@Override
	public NavigationHelper getNavigationHelper() {
		return navHelper;
	}
	
	protected WebDriver getWebDriver() {
		return driver;
	}

	protected String getBaseUrl() {
		return baseUrl;
	}

	@Override
	public void stop() {
		if (driver != null) {
			driver.quit();
		}
	}
	
}